Repository navigation
Studio images: family batch adapters, measured batching race and per-size CUDA graphs - #19837
Conversation
…size CUDA graphs Concurrent image requests share a call only where the family's pipeline fuses the rows (batched_forward on the family, today's answer when unset) and, for resident or CUDA-graph loads, only at the batch sizes and shapes an idle race measured as faster on this card (lower 95% bound of the speedup at least 1.05x, batched p95 within 3%). Verdicts, losers included, persist in the probe cache. Unmeasured loads keep the previous rules. A coalesced call records a CUDA graph only for batch sizes 2 and 4 and only during the race, never evicts a size-1 graph, and an out-of-memory recording drops only the batched graphs. Seeded requests join only where the measured path is neighbour-exact and replays from the seed. Status reports batch_trace counters; the idle path dispatches before any key or policy read.
…ace only fused families A request that cannot be part of any admitted batch size at its shape renders at once instead of waiting to coalesce. The race refuses a family that loops one image per forward, and a card without a fingerprint is not re-probed on every status poll.
A losing size never runs batched on that load, so the graphs the race recorded for it would only hold graph pool memory; the size-1 graphs and any winning size stay.
…hind it With only some batch sizes admitted (static compile, a measured winner), a fired batch takes the longest admitted prefix. The members it left out used to render one at a time; they are now told as the batch fires and coalesce again behind it (at most 3 rounds), so 16 waiting requests with an admitted size of 4 run as calls of 4 instead of one call of 4 and 12 single renders.
… images one at a time FBCache decides whether to skip the remaining blocks from one mean residual over the whole call, so in a shared call one request's image would decide another's. An explicit FBCache load now serves serially, an AUTO cache admits no batch size at a step count where it engages FBCache, and the race refuses; the static schedule decides by step only and still batches. The Qwen-Image single-frame VAE path decoded every image of a call in one pass. Inside a call carrying several requests it now decodes one image per pass, so the peak is one feature map and each image decodes exactly as its own request would; a single user's multi-image call keeps its one batched pass.
…counter installed
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
… verdicts by step count A batch that ran out of memory was split into halves while its exception was still alive, and the traceback pinned the failed call's frames and the tensors they hold, so the halves started with that memory allocated. The tracebacks are now dropped before the halves run. Race verdicts are now keyed by step count as well as canvas and guidance: the fixed per-call cost weighs more at few steps, so a win at one step count says little about another. Adds a CUDA test that a size-2 graph replays next to the size-1 graph with no host sync, in the shared graph pool. [skip ci]
…-image graph The image scope keys on the reference shapes, so each new edit reference size warms and records, and a full planned cache (Qwen-Image-2.1's step) evicted the least recently replayed graph. With true CFG, three edit reference sizes are six new keys and evicted both text-to-image graphs, so the next plain render warmed and recorded again on the user's request. A full planned cache now drops a batched graph first, then an edit's; an edit that would have to drop a text-to-image graph runs ungraphed instead. [skip ci]
… the race records the largest size first torch frees a graph pool's blocks only once no graph uses it, so with every graph in one pool, dropping the batch-size graphs (a race loss, an OOM) gave back nothing while the size-1 graphs lived. Batched graphs now record into a pool of their own, shared by every batched graph (UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL=shared records them beside the size-1 graphs as before). Batched graphs also have their own budget (MAX_BATCHED_GRAPHS), so they never take the slot of a size-1 prompt-length variant, and the race records the largest batch size first so smaller ones reuse its blocks.
…hs bypassed It called a bypass() the graph handles do not have, so the arm silently timed the batched call with its graphs; it now uses set_bypass.
The cards the host shows and how the load spans them (component split, CFG replica, layer split) are now part of the verdict key, so a race on one card never decides a two-card load and the other way round.
A graphed race verdict admits its size only while the load holds that batch-size graph; otherwise the eager arm's own verdict applies, with seeded joins off. Batched recording is refused on offloaded loads, and an OOM while recording one runs the call like the other unrecorded shapes. The admission estimate is k times the size-1 graph's own pool growth, with free memory read on the operands' card. A batched key that a size-1 call replays becomes a size-1 graph, and a placement change clears the batched and edit labels. [skip ci]
…at was measured A seeded request joins only when every batch size it could render at has a neighbour- and replay-exact verdict, so a streamed load that still admits unmeasured sizes keeps seeded requests alone. When the eager arm wins a size, the race drops that size's recorded graphs, so dispatch runs the arm that was measured. The race derives the static-compile size limit from the load's compile state, since resident and graphed loads answer serial before the compiled-sizes rule.
Fast CFG is set per pipeline call, so requests with different cfg_interval_end values must never share one. The key already carries every generate kwarg; this test keeps it that way, with a same-interval control that still batches. [skip ci]
… layout, an OOM size is a loss generate() re-arms the CUDA graphs before every chunk, which undid the race's eager-arm bypass; a forced_eager() scope now keeps every handle eager through it. A verdict won by graph replay records the prompt layout it was raced at and holds only for requests in that layout, so another T5 bucket falls back to the eager arm's verdict. A capacity failure at one batch size is persisted as a loss with its reason, its graphs are dropped and the cache emptied, and the race goes on to the smaller sizes. [skip ci]
…-up recorded A request arriving after the batched warm-up aborted the size before the drop, so the graph it recorded kept its static buffers and pool until a reset or unload, though no verdict could ever admit it. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7859edb98e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return None | ||
| if family: | ||
| try: | ||
| fused = batched_forward(detect_family("", family)) |
There was a problem hiding this comment.
Preserve the load-aware MOSS batching capability check
For a MOSS load eligible for layer-major batching, this check always rejects coalescing because it calls batched_forward() without the loaded pipeline. _moss_layer_major() consequently sees no transformer and returns false, even when diffusion_moss_image.coalesce_key(state.pipe) permits batching (including the shipped A100-SXM4-80GB configuration). Both image request routes therefore render these requests individually despite the backend allowing them. Defer this load-dependent decision to coalesce_plan() or pass the actual pipeline into the capability check.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3e8503c312: the route now asks admits_without_pipe(family), which still refuses at once when a family's answer cannot depend on the load but leaves MOSS to coalesce_plan(), where coalesce_key(state.pipe) sees the real pipeline. Layer-major MOSS loads coalesce again on both image routes. New route test: a streamed MOSS load whose coalesce_key allows layer-major coalesces two waiting requests into one call (fails before the fix); a control with coalesce_key None still renders both alone.
| if not verdict.get("promoted") or verdict.get("arm") == "batched_eager": | ||
| # A losing size never runs batched here, and an eager-won size must not replay the graphs the race | ||
| # recorded (dispatch never bypasses them; user calls never record new ones): drop that size's graphs (their | ||
| # own pool returns to the card; under BATCH_POOL_ENV=shared they stay in the one pool). | ||
| verdict["batched_graphs_dropped"] = _drop_batched(handles, size) |
There was a problem hiding this comment.
Enforce eager race winners for block-graph loads
On a load using BlockGraphSet, an eager-arm win does not actually switch subsequent coalesced requests to eager execution: _drop_batched() skips these handles because they have no drop_batched() method, and generate() re-enables them through cuda_graph.set_bypass() before each chunk. effective_verdict() nevertheless accepts the eager winner unchanged. With an eager G2c PASS, this admits requests using the graph path that lost the race and may lack a graph quality PASS; the seeded reproducibility checks also describe a different execution path. Apply a per-call bypass for eager-winning sizes, or withhold their promotion when the handle cannot enforce that path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3e8503c312 by withholding promotion: an eager-arm win now stands only when every graph handle can drop its batched graphs (drop_batched). The race records why it withheld one, and effective_verdict() applies the same rule to saved verdicts, including a graphed win that falls back to its eager arm. New test: a fast eager win on block-graph-style handles is not promoted by the race or from a saved verdict (fails before the fix); a control with drop_batched still promotes.
…needs handles that can stay eager The route's family check has no pipe, so for MOSS (which fuses rows only on a measured layer-major load, decided from the pipe) it always refused, and both image routes rendered MOSS one at a time despite #19957. The route now refuses only when the answer cannot depend on the load and leaves MOSS to coalesce_plan, which asks coalesce_key with the real pipe. On handles that record graphs on demand (block graphs, no drop_batched) an eager-arm win could not keep later coalesced calls eager: they would replay graphs again while the verdict said eager. Such a win is now withheld, both when the race decides and when a saved verdict is applied (including a graphed win falling back to its eager arm). [skip ci]
|
@codex review |
…olds host RAM (copies drifted since zoo #2909) (#19999) ## Problem `tests/utils/test_dataset_num_proc.py::test_the_two_copies_have_not_drifted` fails on every `Core` leg, for example on the #19837 and #19781 staging runs on current main: ``` AssertionError: unsloth/dataset_num_proc.py and unsloth_zoo/dataset_num_proc.py have diverged; the zoo copy is the source of truth ``` unsloth-zoo #2909 taught `unsloth_zoo/dataset_num_proc.py` to keep `Dataset.map` in-process while `offload_layers` holds model layers page-locked in host RAM. Linux copies that memory into every forked worker at fork time, and a 120 GB host tier with 6 workers stalled the map at 0 rows. The change adds `_offload_reason()` and returns it from `_workers_unusable_reason()`. The fallback copy in unsloth, which is used when the installed zoo has no `dataset_num_proc`, did not get the same change. The guard is right: the zoo copy is the source of truth. ## Fix Port the same `_offload_reason()` into `unsloth/dataset_num_proc.py` and return it from `_workers_unusable_reason()`, matching the zoo code exactly. Like the zoo version, it reads `unsloth_zoo.block_swap.offload_active` only if that module is already loaded, so nothing new is imported. ## Verification With unsloth-zoo main (`cf4eb46`) on the path: - `tests/utils/test_dataset_num_proc.py`: 106 passed. - Before, on main's copy: `test_the_two_copies_have_not_drifted` failed (1 failed, 105 passed).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 917383519c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| try: | ||
| found = diffusion_batch_race.lookup( | ||
| state, width, height, guidance, range(2, batch_max() + 1), steps = steps | ||
| ) |
There was a problem hiding this comment.
Exclude unmeasured adapter sets from measured batching admission
After an adapter-free resident load records an eager batching win with a quality PASS, the same verdict also authorizes batching when LoRAs are subsequently applied or the model is reloaded with adapters: load_key() excludes adapters, and this lookup never checks _race_adapters_active(). The refusal in batch_race() only prevents measuring adapted loads; it does not prevent consuming the base model's verdicts. Consequently, an otherwise serial adapted load can enter measured batching, including automatic explicitly seeded joins based on the base model's bit-exact checks. Reject adapter-bearing loads and requests when consuming these verdicts, or include the adapter selection in the measurement identity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6e6b15b. _measured_sizes now returns no verdicts when the load carries adapters with a non-zero weight (applied, baked in, or requested at load, the same check the race uses to refuse). An adapted load therefore keeps today's rules: a resident or graphed load serves one request at a time, a streamed load keeps its unmeasured default, and coalesce_seeded_ok is False, so an explicitly seeded request never joins on the base model's exactness. A zero-weight adapter still reads the base verdicts. New test test_an_adapted_load_never_consumes_the_adapter_free_verdicts fails before the change.
…since #19965) (#20004) ## Problem `tests/test_triton_constexpr_comments.py::test_every_constexpr_line_has_a_comment` fails on main (`53a74eb64e`) in `Repo tests (CPU, rest)`: ``` tl.constexpr parameters without a comment: unsloth/kernels/int8_lora.py:213 _int8_mm_kernel.BLOCK_M unsloth/kernels/int8_lora.py:214 _int8_mm_kernel.BLOCK_N unsloth/kernels/int8_lora.py:215 _int8_mm_kernel.BLOCK_K unsloth/kernels/int8_lora.py:216 _int8_mm_kernel.GROUP_M unsloth/kernels/int8_lora.py:264 _int8_dgrad_kernel.HAS_D unsloth/kernels/int8_lora.py:265 _int8_dgrad_kernel.INV_SQRT_G unsloth/kernels/int8_lora.py:267 _int8_dgrad_kernel.BLOCK_M unsloth/kernels/int8_lora.py:269 _int8_dgrad_kernel.GROUP_M ``` #19965 added `unsloth/kernels/int8_lora.py`, and these eight parameters have no comment. It shows on any PR whose `rest` shard runs, for example the #19837 staging run. ## Fix Comments only, no code change. Each of the eight parameters gets a one-line comment saying what it is: - the tile sizes - the `K % BLOCK_K == 0` precondition that lets the K loop load unmasked - the swizzle group - the dgrad epilogue add - the `1 / sqrt(G)` normalisation ## Verification - `tests/test_triton_constexpr_comments.py`: 4 passed. Before, on main: 1 failed, listing the eight parameters above. - `ruff format` and `ruff check`: clean.
…ng verdicts [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6e6b15b444
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not isinstance(verdict, dict) or verdict.get("arm") != "batched": | ||
| return verdict |
There was a problem hiding this comment.
Revalidate eager winners when later races install matching graphs
If a size wins on the eager arm at canvas A, then a later race wins on the graph arm at canvas B with the same tensor shapes (for example, the same dimensions and guidance but a different step count), this early return still admits A as eager. The second race has installed a graph that GraphedForward will replay for A, and the request route does not force eager execution. Having drop_batched() only enforces the winner immediately after its race; it does not prevent later captures from changing that path. Consequently, an eager-only quality PASS and eager reproducibility checks can authorize graph-backed requests. Force the recorded eager path per request, or withhold its verdict whenever matching graphs have subsequently appeared.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6332acb. effective_verdict now withholds any promoted eager-path verdict (an eager-arm win, or a graphed win falling back to its eager arm) while a step-graph handle holds a batch-size graph of that size. Graphs key on tensor shapes, and a later race at another canvas or step count can record one with the same shapes, so the eager path could no longer be guaranteed. Withheld sizes fall back to serial, and seeded joins are refused with them. A graphed win at its own canvas and layout still holds, and other sizes are unaffected. New test test_an_eager_win_is_withheld_once_a_later_race_records_a_graph_of_that_size fails before the change; 338 batching and graph tests pass.
…date banner layout red since #19970) (#20005) ## Problem The update banner layout check (`tests/studio/playwright_update_banner_layout.py`) fails 6 of its 2159 checks on main. It fails on the Linux `Chat UI Tests (chat)` leg, the Windows `Chat UI Tests` leg and the Mac `Chat UI, API, Update and GGUF inference` leg, on every staging run built on current main, for example #19837, #14119, #14292, #15300 and #19627: ``` [banner] FAIL 921x534 new chat expanded: the bottom card is on the corner, not floating above it lastPaintedFromBottom=4 (want 16) [banner] FAIL 390x500 new chat collapsed: the bottom card is on the corner, not floating above it lastPaintedFromBottom=9.1 (want 16) ``` The other four failures are the same check on the Train and Model hub pages, at the same two sizes. The cards in the corner rail (update, llama.cpp update, downloads, loaded models) are supposed to sit 16 px above the corner. At these two window sizes the bottom card lands 4 px and 9 px from the edge instead. #19970 made the rail `overflow: visible` while its cards fit, and scroll only once they outgrow it (`data-rail-scrolls`), so WebKit can blur glass cards against the page. That part is right. But `overlayRailScope` decided "outgrow" with `scrollHeight > clientHeight`, and for an `overflow: visible` box Chromium leaves the end padding out of `scrollHeight`. Cards that run into the rail's 16 px bottom padding, but not past its border, read as `scrollHeight == clientHeight`: the rail never starts scrolling, and the bottom card sits in the gutter. The same 921x534 layout on a bare page in Chromium, cards running 12 px into the bottom padding: | rail | `scrollHeight` / `clientHeight` | bottom card from the corner | |---|---|---| | `overflow: visible` (main) | 534 / 534 | 4 px, and the rail does not scroll | | `overflow: auto` (before #19970) | 546 / 534 | scrolls | Before #19970 the rail was always a scroll container, so the same layout scrolled. ## Fix `railOverflows()` in `studio/frontend/src/lib/toast-offset.ts`: - It keeps the `scrollHeight` test. - It also measures the span of the rail's in-flow cards plus its top and bottom padding against `clientHeight`. Dragged cards are `fixed` elsewhere and are left out. - `overlayRailScope` uses it, so the rail scrolls whenever its cards do not fit. - While they fit, the rail stays `overflow: visible`, so #19970's WebKit glass fix is unchanged. On the bare page above: - Cards 12 px into the padding: the old test reports no overflow, `railOverflows` reports overflow. - Cards that fit with room to spare: both report no overflow, and the bottom card sits at 16 px. ## Verification - `tests/toast-offset.test.ts`, new case: cards running into the bottom padding with `scrollHeight == clientHeight` count as overflow; a fitting stack, a stack with a dragged `fixed` card, and an empty rail do not; a real `scrollHeight` overflow still does. `toast-offset.test.ts` and `glass-floating-cards.test.ts`: 27 passed. - `npm run typecheck` and `eslint` on both files: clean. - The browser check itself, `tests/studio/playwright_update_banner_layout.py`, run against a local Studio install of main (`6047d3b980`) with the same driver CI uses: - Before, main: `2159 checks, 6 failed`. The same six as CI: 921x534 expanded and 390x500 collapsed on New chat, Train and Model hub, `lastPaintedFromBottom=4` / `9.1`. - After, the same install with only this PR's `toast-offset.ts` rebuilt in: `2153 checks, 0 failed`. - The six corner checks are not run in those six layouts any more, because the rail now scrolls there, exactly as it did before #19970. The check only judges the corner while the rail is not scrolling. Every other check, including "can be scrolled into the rail's view" for each card, passes on both sides. ## Screenshots Bottom-right corner of the two failing layouts, from the driver's own screenshots of the run above. At rest the pixels are the same on both sides: the stack does not fit these windows, and the bottom card runs into the gutter either way. What changes is that the rail is a scroll container again when its cards outgrow it, as before #19970, rather than an `overflow: visible` box that lets them spill into its padding. 
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci run |
# Conflicts: # studio/backend/core/inference/diffusion_cuda_graph.py [skip ci]
|
pre-commit.ci run |
…ein 2.69x per 4 images on A100), Anima kept serial (unslothai#20071) Follows unslothai#19837 (merged), which added the batch adapters and the measured race. ## Problem FLUX.3 klein, FLUX.3 klein base and Anima render every image of a list as its own modular pipeline call: the text step encodes one prompt per call, so unslothai#19837's request batching has to treat both families as `batched_forward = False` and runs concurrent requests one at a time. When the denoiser streams weights from host memory, every image pays the full weight transfer again, so four queued requests cost four full passes of streaming. ## Change - **FLUX.3** (`diffusion_flux3.py`): rows that share a text window run as one modular call. Each row is encoded alone, so its embeddings are exactly what its own call would produce; the text step returns the stacked rows, each row's noise is its own seeded reference noise, and the denoiser runs one forward per step over all rows. Rows land in separate calls when they differ in text window, per-row negative prompt or per-row reference size, and also for caller latents, unseeded rows, or a denoiser whose activation scale is computed from the whole call. A single image takes the unchanged call. - **FLUX.3 edit, shared reference**: within one request (one prompt, a seed list), rows that share the request's reference still run as one call. A neighbour swap on that path was bit-identical (see the follow-up section). The route never coalesces separate edit requests: only plain text-to-image requests share a call. - **FLUX.3 per-row references** (`row_images`, references per image): held back. Rows that carry their own references always render one at a time until a GPU run shows neighbour invariance. `UNSLOTH_DIFFUSION_FLUX3_ROW_REFS_BATCH=1` enables batching for measurement only. - **Anima** (`diffusion_anima.py`): the facade can run rows with the same conditioned text length as one modular call, but the Anima record keeps `batched_forward = False`, so Anima requests stay serial on every card (one chunk per image, never coalesced at the route). On an RTX PRO 6000 its batched rows drifted about 0.13 LPIPS from their own solo renders; batching turns on only after a like-for-like G2c passes. - Quality gate (`diffusion_batch_quality.py`, merged in from the infra side): a measured race win serves only with a passing offline G2c verdict for the family, the card's device class and the execution path; missing or failing keeps the serial rule. The race's replay check now compares row 0 with its solo render on the same execution path (`b_exact`: bit-identical, or within the same-shape rerun noise), and seeded joins need it. - `diffusion_families.py`: `DiffusionFamily.batched_forward` (None = not stated, the existing default rules). Both FLUX.3 records set it to True, so unslothai#19837's adapter (`diffusion_batch_adapters.batched_forward` / `adapter_for`) admits them, `_generation_chunks` keeps their rows in one chunk, and the race no longer refuses them. - Kill switches: `UNSLOTH_DIFFUSION_FLUX3_BATCH=0` and `UNSLOTH_DIFFUSION_ANIMA_BATCH=0` restore one call per image. ## What Auto does by default Nothing changes for a single-image request. With concurrent requests, unslothai#19837's policy decides: - **Streamed denoiser** (Low VRAM / group offload, no CUDA graphs): requests with the same settings share a call (the existing rule for a family that fuses its rows). - **Resident weights, CUDA graphs, or a static compile**: requests stay serial, as they do today, unless unslothai#19837's idle race measures a win on that load, card and shape **and** an offline G2c verdict passes for that family, card and execution path (eager or graph). Without a passing verdict a race win is persisted but not served. The gate ships with no verdicts, so out of the box these placements stay serial; the race decides speed per card, the G2c verdict decides whether that speed may be served. ## Gates - G1: an N=1 single-image request is byte-identical to the base. A request with `batch_size` > 1 now shares one forward across its images, so its bytes may differ from the base by floating-point batch-shape effects; that path is gated by G2a and G2c instead. - G2a: a row's bytes do not change when its neighbours change. - G2c: paired LPIPS against a bf16 speed-off reference, upper bound of (batched minus solo) at most +0.01. - G4: speed lower bound at least 1.05x with p95 at most +3%. 1024 px, Studio Auto settings. **A100 / RTX PRO 6000, batch 4, direct engine calls** (the change on an earlier base): | Family | G1 (N=1 bytes) | G2a (neighbour swap) | G2c upper bound | Streamed batch-4 | Resident batch-4 | |---|---|---|---|---|---| | FLUX.3 klein (16 steps) | identical 4/4 | bit-identical, targets 0/1/3, max diff 0 | +0.0061 (n=24, PASS) | 2.69x (31.0 s to 11.6 s per 4, A100-80) | 1.018x (A100-80) | | FLUX.3 klein base (50 steps) | identical 4/4 | bit-identical, max diff 0 | +0.0050 (n=12, PASS) | 1.33x (44.1 s to 33.2 s, RTX PRO 6000) | 1.016x (A100-40) | | Anima (30 steps) | identical 4/4 | bit-identical, max diff 0 | +0.0006 (n=24, PASS) | 2.43x (45.5 s to 18.7 s, A100-40) | 1.08x (bf16, A100-40) | Every batched render ran one denoiser forward per step over 4 rows (trace: 16 / 100 / 60 calls per batch, the same as one solo image). A/A repeats of the same batch were byte-identical. **G4 (RTX PRO 6000 Blackwell), through unslothai#19837's route and race, this branch merged with unslothai#19837, streamed (Low VRAM)**: | Family | G1 (N=1 bytes vs unslothai#19837) | G2a (race neighbour check) | G2c upper bound | Race | Concurrent N=4 after the race | |---|---|---|---|---|---| | FLUX.3 klein | identical 8/8 | exact (max diff 0), A/A exact | **+0.0061 (n=24, PASS)** on both the eager and the graph path (an earlier n=8 run read +0.0136, under-powered) | size 2 won, **lower bound 1.141x** (eager arm); size 4 skipped (no static-compile graph at 4) | 34.2 vs 32.3 images/min (+6%) | | Anima | 0/10 identical (this load has cudnn benchmark on, which picks conv kernels per process; an A/A base-vs-base arm is queued to tell that apart from a change) | exact (max diff 0), A/A exact; row 0 vs its solo max 227 px | +0.036 vs eager reference (n=8, FAIL); +0.207 strict vs solo | size 2 lost on speed, lower bound 1.036x; size 4 skipped | 22.2 vs 22.2 images/min (no change: stays serial) | On G4 a streamed klein render is already fast (1.85 s per image), so streaming saves little and the speedup is small; the measured race decides per card. This PR ships the klein G2c PASS for this card (RTX PRO 6000 Blackwell, eager and graph path) as a stored quality verdict, so a klein race win there may serve, and only where that card's own race measures a lower bound of at least 1.05x. Every other card, and klein base, still needs its own verdict. Like for like on G4 (n=24): solo renders are byte-identical on the eager and the graph path, and batched rows score the same on both, so the earlier drift was not a path mix. Batched rows are not byte-identical to their solo renders (mean LPIPS 0.010), so seeded requests do not join: the first batch-shape divergence is the bf16 timestep embedder and the text input projection, both run at M = batch rows. Running those row by row is being measured as an exact path and is not part of this PR. On G4 the Anima race also found no speedup, and its batched rows drift far from their solo renders, so this PR keeps Anima serial everywhere (see Change). ## Follow-up: edit batching Batching edits across requests, and rows with per-row references, is left for a follow-up. Evidence so far, kept for that PR: - FLUX.3 klein edit, shared reference, batch 4: G1 identical 4/4; G2a bit-identical (max diff 0, RTX PRO 6000); G2c upper bound +0.00003 (n=12, PASS); resident 1.018x; streamed not measured. - Per-row references: own-row LPIPS at most 0.0044, but in one earlier run one of four targets changed bytes when a neighbour's reference was swapped, so strict G2a is not shown. That is why this PR keeps them serial. ## Tests CPU, `studio/backend`: - New `tests/test_diffusion_flux3_batch_rows.py` and `tests/test_diffusion_anima_batch_rows.py`. They check that edit rows with different references never share a forward and that edit requests with references never coalesce at the route, as well as one forward per step for every row, that each row is its own render, that a neighbour never changes a row, that different text windows / negatives / reference sizes render apart, the kill switch, unseeded rows and per-call scaled denoisers, and that a single image is the unbatched call. - Updated `tests/test_diffusion_flux3.py` (FLUX.3 images share one generation chunk; a record that does not state `batched_forward` keeps one chunk per image) and `tests/test_image_batch_infra.py` (the route's family check now admits FLUX.3). - Run together with `test_image_batch_infra.py`, `test_image_batching_followups.py`, `test_diffusion_batched.py`, `test_batch_sizes_per_load.py`, `test_openai_images_batching.py`, `test_take_rows_batched.py`, `test_diffusion_cfg_batch_policy.py` and every `test_diffusion_flux3_*` / Anima test, plus the quality gate tests (`test_image_batch_quality.py`): 938 passed, 14 skipped. ## Not proven here - The A100 table comes from the same change on an earlier base. The G4 table ran this branch merged with unslothai#19837, before the edit hold-back and the quality gate commits (neither changes a plain text-to-image render). - The quality gate ships with no G2c verdicts, so no family is promoted beyond today's rules until verdicts are measured and added. - Edit batching across requests and per-row references: see the follow-up section above. - No G4 lower bound or p95 was computed. Only medians of 3 interleaved repeats. - No AMD, Apple Silicon or Windows runs. The change is backend Python with no platform-specific code.
Summary
Builds on #19667 (merged). Concurrent image requests from different accounts now share one pipeline call only where it is measured to help, and the batching decision moves from blanket per-family refusals to a per-family capability plus a measured verdict per card, load and shape. Unmeasured loads keep the #19667 rules, so nothing changes until a race on that card proves a win.
Where Auto now batches. In the measured runs, Auto batched only HiDream-I1-Fast streamed on an A100 40GB. Its race promoted batch 4 (median 1.44x, lower bound 1.40x) and batch 2 (lower bound 1.06x), and 16 concurrent users went from 6.4 to 8.0 images/min with p95 down from 149 s to 120 s. FLUX.2 klein 4B resident on RTX PRO 6000 measured 1.037x at batch 2 and 1.055x at batch 4, below the 1.05 lower bound, so it stays one request at a time, byte-identical to before.
Klein accuracy. At batch 4, klein's rows are 0.064 LPIPS from the eager reference, against 0.028 for solo renders, so the paired gate fails at eps 0.01. This is the existing batch-shape behaviour of the INT8 path: neighbour invariance is bit-identical at batch 2 and 4, and a single request with
batch_size4 gets the same drift today. Auto does not batch klein.Family capability.
batched_forwardis read from the family object withgetattr.DiffusionFamilyis unchanged here; families opt in by setting the attribute in their own PRs.What changed
Family capability (
core/inference/diffusion_batch_adapters.py, new)batched_forward(bool) on the family object. Unset keeps today's answer: FLUX.3, Anima, layered, MiniMax-H3-Image, MOSS and Qwen-Image-2.1 render one image per forward; everything else uses the diffusers list call.BatchAdapter(preparegives the row layout key,compatible,denoise_batched,split) withDefaultAdapterfor the list call (FLUX.1 T5 bucket, SD / SDXL CLIP chunk counts). A family can setbatch_adapterfor its own row layout.Measured race (
core/inference/diffusion_batch_race.py, new)POST /api/inference/images/batching/race(owner only) races k requests served one at a time against the same k in one call, at sizes 2 and 4 by default, each arm including encode, denoise and decode, interleaved in random order over several repeats. With CUDA graphs on it also races the batched call with the graphs bypassed (set_bypass). Static compile races only sizes already compiled.diffusion_probe_cache.Namespace("batch_race"): keyed by torch, driver, card and env (the probe fingerprint) plus model and revision, family, denoiser class, precision, speed mode, attention backend, offload placement, graph and compile state, step cache, canvas, guidance, step count and batch size.Policy (
diffusion.py)request_batchingkeeps per-call dynamic NVFP4 serial and serves families without a batched forward serially. Resident and CUDA-graph loads stay serial unless a race promoted a size on this load (new modemeasured). In that mode only the winning sizes and shapes are admitted.coalesce_batch_sizesdrops measured losers and adds measured winners at that shape. A request that cannot be part of any admitted size at its shape no longer waits to coalesce.coalesce_seeded_ok), at every batch size the request could render at. A streamed load that still admits unmeasured sizes keeps seeded requests alone. The env switch still opts every seeded request in.forced_eager()scope that the per-chunk graph re-arm ingenerate()cannot undo.Row coupling outside the denoiser
Out-of-memory retry (
image_request_batching.py)Re-coalescing (
image_request_batching.py)CUDA graphs per batch size (
diffusion_cuda_graph.py)batch_rows(k). It may record a graph of its own only at sizes 2 and 4, only during the race (never on a user's request), at most 2 per module, and within the pool budget (UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL_MB, else free VRAM minus 1 GiB). The estimate is k times the size-1 graph's own pool growth, measured around its capture, not the whole shared pool. Free VRAM is read on the card the call's operands are on.UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL=sharedkeeps one pool, and with it dropping batched graphs returns no VRAM until the size-1 graphs go too.Trace (
core/inference/diffusion_batch_trace.py, new; statusbatch_trace)UNSLOTH_STUDIO_IMAGE_BATCH_TRACE=1: denoiser invocations, rows and block executions per call. A pipeline that loops over the rows of one call shows up as invocations growing with the rows.Unchanged
Tests
tests/test_image_batch_infra.py(new) and the batched-graph tests added totests/test_diffusion_cuda_graph.py. They cover:GPU evidence
Every arm ran in its own fresh process on the same VM, through the real
/api/inference/images/generateroute, with one account per client. The arms were:mainat the Studio images: coalesce identical requests across users, batch plain /images/generate, first-come-first-served slot #19667 merge base;fair: Studio images: coalesce identical requests across users, batch plain /images/generate, first-come-first-served slot #19667 withUNSLOTH_STUDIO_IMAGE_BATCH_MAX=1;ref: an eager reference (speed mode off);Images are 1024x1024. N is the number of concurrent clients in one synchronized burst, 3 repeats each.
FLUX.2 klein 4B, RTX PRO 6000 (Auto: INT8, compiled, CUDA graphs, resident)
batch_size4.HiDream-I1-Fast, A100 40GB (Auto: INT8, group offload, CUDA graphs requested; their capture falls back to eager on #19667 too)
measured.HiDream N=16 in one process, before the race (#19667 rules, serial) and after it (batch 4 promoted, lower bound 1.40x), before the re-coalescing change:
In that run, the members a batch of 4 left out rendered alone. The re-coalescing change addresses this.
The same model and card with re-coalescing (the race promoted both 2 and 4, with lower bounds of 1.06x and 1.40x):
Batch-size graphs on a real card (Tesla T4)
tests/test_diffusion_cuda_graph_batch_gpu.pyrecords a size-1 and a size-2 graph in the one shared pool.torch.cuda.set_sync_debug_mode("error")and match the eager step.Graph pool probe (L4, synthetic 6-block MLP DiT, 4608 tokens x 3072, fp16)
Each row captures size 1, then sizes 2 and 4. It then drops the batched graphs and calls
release_cached_outside_capture().UNSLOTH_DIFFUSION_BATCH_GRAPH_POOL=sharedkeeps one pool for anyone who prefers the lower steady cost.What the trace shows
Not shown
Quality gate on promotion (0d7d96d)
A measured race win now serves only with a stored passing G2c verdict for the same (family, card model, execution path): PASS, at least 24 pairs, 95% CI upper bound of the paired LPIPS difference at most +0.01. A missing, failing or under-powered verdict keeps today's serial rule; the speed verdict is still saved and the race report says per size whether the win serves and why not. The shipped verdict table starts empty, so every race-promoted family (including HiDream on A100) stays serial until a G2c verdict is measured and added. Motivation: FLUX.2 klein on an RTX PRO 6000 won the speed race at size 2 (1.141x lower bound) but failed G2c (+0.0136 at n=8). Test:
test_image_batch_quality.py(a speed-winning race with no G2c pass stays serial).